<?php
class AjaxController extends \Phalcon\Mvc\Controller{
    public function initialize(){
        header("Content-type:text/html;charset=utf-8");
    }
    //注册-验证用户名
    public function checknameAction(){
		if($this->request->isPost()){
			if($this->request->isAjax()){
				$data=$this->request->getPost();			
				$pattern='/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}_]{3,15}$/u';
				if(preg_match($pattern, $data['userName'])){
					$condition="user_name=?1";
	        		$param=array(1=>$data['userName']);
					$user=User::findFirst(array(
			            $condition,
			            "bind"=>$param
			        ));
					if($user->user_id>0){
			            echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>此用户名已存在.</span>"));exit;
			        }else{
			        	echo json_encode(array("status"=>1,"msg"=>"<span class='formtips onSuccess' style='color:#008000;'>√</span>"));exit;
			        }					
				}else{
					echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>4-16个字符，可以有中文.</span>"));exit;
				}				
			}
		}
	}
    //注册-验证密码
    public function checkpasswordAction(){
    	if($this->request->isPost()){
			if($this->request->isAjax()){
		    	$data=$this->request->getPost();
		        $pattern='/^[0-9a-zA-Z][0-9a-zA-Z]{5,13}$/';
				if(preg_match($pattern, $data['userPwd'])){
					echo json_encode(array("status"=>1,"msg"=>"<span class='formtips onSuccess' style='color:#008000;'>√</span>"));exit;
				}else{
					echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>6-14位大小字母或数字.</span>"));exit;
				}
			}
		}
    }
    //注册-验证两次密码输入是否一致
	public function checkrepasswordAction(){
    	if($this->request->isPost()){
			if($this->request->isAjax()){
		    	$data=$this->request->getPost();
		        $pattern='/^[0-9a-zA-Z][0-9a-zA-Z]{5,13}$/';
				if(preg_match($pattern, $data['rePwd'])){
					if($data['rePwd']==$data['userPwd']){
						echo json_encode(array("status"=>1,"msg"=>"<span class='formtips onSuccess' style='color:#008000;'>√</span>"));exit;
					}else{
						echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>再次密码输入不一致.</span>"));exit;
					}					
				}else{
					echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>6-14位大小字母或数字.</span>"));exit;
				}
			}
		}
    }
    //注册-验证QQ号
    public function checkqqAction(){
        if($this->request->isPost()){
			if($this->request->isAjax()){				
		    	$data=$this->request->getPost();
				$pattern='/^[1-9][0-9]{4,}$/';		      
				if(preg_match($pattern, $data['qq'])){					
					echo json_encode(array("status"=>1,"msg"=>"<span class='formtips onSuccess' style='color:#008000;'>√</span>"));exit;							
				}else{
					echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>请输入正确的QQ号.</span>"));exit;
				}
			}
		}
    }
    //注册-验证手机号
	public function checkmobileAction(){
        if($this->request->isPost()){
			if($this->request->isAjax()){				
		    	$data=$this->request->getPost();
				$pattern='/^1[3|4|5|7|8]\d{9}$/';		      
				if(preg_match($pattern, $data['mobile'])){					
					echo json_encode(array("status"=>1,"msg"=>"<span class='formtips onSuccess' style='color:#008000;'>√</span>"));exit;							
				}else{
					echo json_encode(array("status"=>0,"msg"=>"<span class='formtips onError'>请输入正确的手机号.</span>"));exit;
				}
			}
		}
    }
    //注册
	public function doregisterAction(){
		if($this->request->isPost()){
			if($this->request->isAjax()){
				$data=$this->request->getPost();
				$sessionCode=strtolower($this->session->get('code'));
				$postCode=strtolower($data['code']);
				if($sessionCode!=$postCode){
					echo json_encode(array("status"=>0));exit;
				}
				$pattern='/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}_]{3,15}$/u';
				if(preg_match($pattern, $data['user_name'])){
					$condition="user_name=?1";
	        		$param=array(1=>$data['userName']);
					$user=User::findFirst(array(
			            $condition,
			            "bind"=>$param
			        ));
					if($user->user_id>0){
			            echo json_encode(array("status"=>0));exit;
			        }			
				}else{
					echo json_encode(array("status"=>0));exit;
				}
				$pattern='/^[0-9a-zA-Z][0-9a-zA-Z]{5,13}$/';
				if(!preg_match($pattern, $data['user_pwd'])){
					echo json_encode(array("status"=>0));exit;
				}
				if(!preg_match($pattern, $data['rePwd'])){
					echo json_encode(array("status"=>0));exit;
				}
				if($data['user_pwd']!=$data['rePwd']){
					echo json_encode(array("status"=>0));exit;
				}
				$pattern='/^[1-9][0-9]{4,}$/';		      
				if(!preg_match($pattern, $data['user_qq'])){					
					echo json_encode(array("status"=>0));exit;							
				}
				$pattern='/^1[3|4|5|7|8]\d{9}$/';		      
				if(!preg_match($pattern, $data['user_mobile'])){					
					echo json_encode(array("status"=>0));exit;								
				}
				unset($data['code'],$data['rePwd']);
				$data['user_pwd']=sha1($data['user_pwd']);
				$data['user_reg_time']=time();
				$data['user_ip']=$_SERVER["REMOTE_ADDR"];
				$data['user_time']=time();
				$data['user_promote_code']=substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
                if($this->cookies->has('master-id')){
                    $master=$this->cookies->get('master-id');
                    $data['user_master_id']=$master->getValue();
                }
				$user=new User();
				if($user->save($data)){
                    $condition="user_name=?1 and user_pwd=?2";
                    $param=array(1=>$data['user_name'],2=>$data['user_pwd']);
                    $user=User::findFirst(array(
                        $condition,
                        "bind"=>$param
                    ));
                    if($user->user_id>0){
                        $this->session->set('userId',$user->user_id);
                        $this->cookies->set('master-id', '', time() - 100);
                        echo json_encode(array("status"=>1));exit;
                    }else{
                        echo json_encode(array("status"=>0));exit;
                    }
				}else{
					echo json_encode(array("status"=>0));exit;
				}											
			}
		}
	}
    //登录验证
    public function loginAction(){
        if($this->request->isPost()) {
            if ($this->request->isAjax()) {
                $data=$this->request->getPost();
                $condition="user_name=?1 and user_pwd=?2";
                $param=array(1=>$data['userName'],2=>sha1($data['userPwd']));
                $user=User::findFirst(array(
                    $condition,
                    "bind"=>$param
                ));
                if($user->user_id>0){
                    $this->session->set('userId',$user->user_id);
                    echo json_encode(array("status"=>1,"msg"=>"登录成功！"));exit;
                }else{
                    echo json_encode(array("status"=>0,"msg"=>"登录失败！"));exit;
                }
            }
        }
    }
    //对绑定店铺进行启用/禁用操作
    public function shopoperateAction(){
        if($this->request->isPost()) {
            if ($this->request->isAjax()) {
                if($this->session->has('userId')){
                    $data=$this->request->getPost();
                    $shop=Shop::findFirst($data['id']);
                    if($shop->save(array("shop_status"=>$data['v']))){
                        echo json_encode(array("status"=>1,"msg"=>"操作成功！"));exit;
                    }else{
                        echo json_encode(array("status"=>0,"msg"=>"操作失败，请稍候重试！"));exit;
                    }
                }else{
                    echo json_encode(array("status"=>0,"msg"=>"非法操作！"));exit;
                }
            }else{
                $this->response->redirect("/");
            }
        }else{
            $this->response->redirect("/");
        }
    }
    //检查商家是否绑定店铺
    public function checkbindAction(){
        if($this->request->isPost()) {
            if ($this->request->isAjax()) {
                if($this->session->has('userId')){
                    $userId=$this->session->get('userId');
                    $data=$this->request->getPost();
                    if($data['v']==0){
                        $condition="shop_user_id=?1";
                        $param=array(1=>$userId);
                    }else{
                        $condition="shop_user_id=?1 and shop_type=?2";
                        $param=array(1=>$userId,2=>$data['v']);
                    }
                    $shopList=Shop::find(array(
                        $condition,
                        "bind"=>$param
                    ));
                    if($shopList->count()>0){
                        echo json_encode(array("status"=>1));exit;
                    }else{
                        echo json_encode(array("status"=>0));exit;
                    }
                }else{
                    echo json_encode(array("status"=>0));exit;
                }
            }else{
                $this->response->redirect("/");
            }
        }else{
            $this->response->redirect("/");
        }
    }
	//ajax无刷新上传商品图片
	public function uploadthumbAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				if($this->request->hasFiles()){
					$datestr=date('Ymd',time());
					$path='../uploads/'.$datestr.'/';
					if(!file_exists($path)){
						mkdir($path);
					}
					$config=Config::findFirst();
					foreach ($this->request->getUploadedFiles() as $file){
						if($file->getName()){
							$type=strtolower($file->getExtension());
							$size=$file->getSize();
							$typearr=array('jpg','png','gif');
							if(!in_array($type,$typearr)){//若图片不是jpg，png或gif格式，则禁止上传
								echo json_encode(array('status'=>0,'info'=>'无法上传此类型的图片！'));exit;
							}
							if($size>2*1024*1024){//若图片大小大于2MB，禁止上传
								echo json_encode(array('status'=>0,'info'=>'图片不能大于2M！'));exit;
							}
							$imgName=date('YmdHis',time()).uniqid().'.'.$type;
							$file->moveTo($path.$imgName);
							$imgSrc=$config->img_domain.$datestr.'/'.$imgName;
						}
					}
					echo json_encode(array('status'=>1,'info'=>$imgSrc));exit;
				}else{
					echo json_encode(array('status'=>0,'info'=>'您还没有选择图片！'));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
	//从淘宝商品链接中抓取商品主图
	public function getimgAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				$data=$this->request->getPost();
				if(preg_match("/taobao.com|tmall.com/",$data['goodsLink'])){
					$shop=Shop::findFirst($data['shopId']);
					$contents=@file_get_contents($data['goodsLink']);
					$contents=@iconv("GBK", "utf-8",$contents);
					if(preg_match("/".$shop->shop_keeper."/",$contents)){
						if(preg_match("/<img id=\"J_ImgBooth\".*?src=\"(.*?)\".*?>/is",$contents,$matches)){
							$imgUrl='https:'.$matches[1];
							$ext=strrchr($imgUrl,'.');
							$datestr=date('Ymd',time());
							$path='../uploads/'.$datestr.'/';
							if(!file_exists($path)){
								mkdir($path);
							}
							$fileName=uniqid().date('His').$ext;
							ob_start();
							if(@readfile($imgUrl)){
								$img=ob_get_contents();
								ob_end_clean();
								if($fp=@fopen($path.$fileName,'a')){
									fwrite($fp,$img);
									fclose($fp);
									$config=Config::findFirst();
									$imgSrc=$config->img_domain.$datestr.'/'.$fileName;
									echo json_encode(array("status"=>1,"msg"=>$imgSrc));exit;
								}else{
									echo json_encode(array("status"=>0,"msg"=>"商品图片获取失败，请稍候重试或手动上传！"));exit;
								}
							}else{
								echo json_encode(array("status"=>0,"msg"=>"商品图片获取失败，请稍候重试或手动上传！"));exit;
							}
						}else{
							echo json_encode(array("status"=>0,"msg"=>"未获取到商品图片，请手动上传！"));exit;
						}
					}else{
						echo json_encode(array("status"=>0,"msg"=>"此链接不是您所选店铺的商品！"));exit;
					}
				}else{
					echo json_encode(array("status"=>0,"msg"=>"请输入正确的商品链接！"));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
	//计算佣金
	public function getfeeAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				if($this->session->has('userId')){
					$taskPrice=0;
					$data=$this->request->getPost();
					$userId=$this->session->get('userId');
					$user=User::findFirst($userId);
					if($user->user_identity==2&&$user->user_type==2){
						//主持
						if($data['level']==0){
							$taskPrice=0;
						}elseif($data['level']==1){
							$taskPrice=3;
						}elseif($data['level']==2){
							$taskPrice=4;
						}elseif($data['level']==3){
							$taskPrice=4.5;
						}elseif($data['level']==4){
							$taskPrice=5;
						}elseif($data['level']==5){
							$taskPrice=5.5;
						}elseif($data['level']==6){
							$taskPrice=6;
						}elseif($data['level']==7){
							$taskPrice=7;
						}
					}else{
						if($data['level']==0){
							$taskPrice=0;
						}elseif($data['level']==1){
							$taskPrice=3;
						}elseif($data['level']==2){
							$taskPrice=4.5;
						}elseif($data['level']==3){
							$taskPrice=5.5;
						}elseif($data['level']==4){
							$taskPrice=6;
						}elseif($data['level']==5){
							$taskPrice=7;
						}elseif($data['level']==6){
							$taskPrice=7.5;
						}elseif($data['level']==7){
							$taskPrice=8;
						}
						if($data['accountType']==1){
							$taskPrice=$taskPrice-1;
						}
					}
					if($data['goodsNum']>1){
						$taskPrice=$taskPrice+($data['goodsNum']-1)*0.5;
					}
					if($data['entrance']==2){
						$taskPrice=$taskPrice+1;
					}
					$priceArr=explode(',',$data['priceStr']);
					$numArr=explode(',',$data['numStr']);
					foreach($priceArr as $k=>$p){
						$taskPrice=$taskPrice+floor($p*$numArr[$k]/200.001)*0.5;
					}
					$taskPrice=$taskPrice+$data['addFee'];
					$taskPrice=$taskPrice<=0?0:$taskPrice;
					echo json_encode(array("status"=>2,"msg"=>$taskPrice));exit;
				}else{
					echo json_encode(array("status"=>1,"msg"=>"您还未登录！"));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
	//发布淘宝任务
	public function releasetbAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				if($this->session->has('userId')){
					$data=$this->request->getPost();
					if($data['task_shop_id']==0){
						echo json_encode(array("status"=>2,"msg"=>"请选择掌柜号！"));exit;
					}
					if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}\_\，\-\s]{1,}$/u',$data['task_summary'])){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的任务摘要！"));exit;
					}
					if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}\_\，\-\s]{1,}$/u',$data['task_search_keywords'])){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的搜索关键词！"));exit;
					}
					if($data['task_search_type']==0){
						echo json_encode(array("status"=>2,"msg"=>"请选择搜索类型！"));exit;
					}
					if($data['task_sort_type']==0){
						echo json_encode(array("status"=>2,"msg"=>"请选择排序方式！"));exit;
					}
					if(!preg_match('/taobao.com|tmall.com/',$data['task_goods_link'])){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品链接！"));exit;
					}
					if(floatval($data['task_goods_price'])<=0){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品价格！"));exit;
					}
					if(intval($data['task_goods_num'])<=0){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品数量！"));exit;
					}
					if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}\_\，\-\s]{1,}$/u',$data['task_goods_prompt'])){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品位置提示！"));exit;
					}
					if($data['task_buyer_level']==0){
						echo json_encode(array("status"=>2,"msg"=>"请选择买号等级！"));exit;
					}
					if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}\_\，\-\s\n]{1,}$/u',$data['task_demand'])){
						echo json_encode(array("status"=>2,"msg"=>"请输入正确的任务需求！"));exit;
					}
					$userId=$this->session->get('userId');
					$data['task_type']=1;
					$data['task_user_id']=$userId;
					$data['task_release_time']=time();
					//计算佣金
					$this->db->begin();
					$user=User::findFirst($userId);
					if($user->user_identity==2&&$user->user_type==2){
						//主持
						if($data['task_buyer_level']==0){
							$taskPrice=0;
						}elseif($data['task_buyer_level']==1){
							$taskPrice=3;
						}elseif($data['task_buyer_level']==2){
							$taskPrice=4;
						}elseif($data['task_buyer_level']==3){
							$taskPrice=4.5;
						}elseif($data['task_buyer_level']==4){
							$taskPrice=5;
						}elseif($data['task_buyer_level']==5){
							$taskPrice=5.5;
						}elseif($data['task_buyer_level']==6){
							$taskPrice=6;
						}elseif($data['task_buyer_level']==7){
							$taskPrice=7;
						}
					}else{
						//普通商家
						if($data['task_buyer_level']==0){
							$taskPrice=0;
						}elseif($data['task_buyer_level']==1){
							$taskPrice=3;
						}elseif($data['task_buyer_level']==2){
							$taskPrice=4.5;
						}elseif($data['task_buyer_level']==3){
							$taskPrice=5.5;
						}elseif($data['task_buyer_level']==4){
							$taskPrice=6;
						}elseif($data['task_buyer_level']==5){
							$taskPrice=7;
						}elseif($data['task_buyer_level']==6){
							$taskPrice=7.5;
						}elseif($data['task_buyer_level']==7){
							$taskPrice=8;
						}
						if($data['task_return_type']==1){
							$taskPrice=$taskPrice-1;
						}
					}
					if($data['task_entrance']==2){
						$taskPrice=$taskPrice+1;
					}
					$taskPrice=$taskPrice+$data['task_add_commission'];
					//拼接添加的商品数量
					$str='';
					foreach($data['goodsNum'] as $v){
						if(intval($v)<=0){
							echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品数量！"));exit;
						}
						$str=$str.$v.',';
					}
					$data['task_goods_nums']=rtrim($str,',');
					//拼接添加的商品链接
					$str='';
					foreach($data['goodsLink'] as $v){
						if(!preg_match('/taobao.com|tmall.com/',$v)){
							echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品链接！"));exit;
						}
						$str=$str.$v.',';
					}
					$data['task_goods_links']=rtrim($str,',');
					//拼接添加的商品价格
					$str='';
					foreach($data['goodsPrice'] as $k=>$v){
						if(floatval($v)<=0){
							echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品价格！"));exit;
						}
						$str=$str.$v.',';
						$data['task_total_price']+=$v*$data['goodsNum'][$k];
						$taskPrice=$taskPrice+0.5;
						$taskPrice=$taskPrice+floor($v*$data['goodsNum'][$k]/200.001)*0.5;
					}
					$data['task_goods_prices']=rtrim($str,',');
					//拼接添加的商品缩略图
					$str='';
					foreach($data['goodsImg'] as $v){
						$str=$str.$v.',';
					}
					$data['task_goods_pictures']=rtrim($str,',');
					//拼接添加的商品位置提示
					$str='';
					foreach($data['searchPosition'] as $v){
						if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}][0-9a-zA-Z\x{4e00}-\x{9fa5}\_\，\-\s]{1,}$/u',$v)){
							echo json_encode(array("status"=>2,"msg"=>"请输入正确的商品位置提示！"));exit;
						}
						$str=$str.$v.',';
					}
					$data['task_goods_prompts']=rtrim($str,',');
					$data['task_total_price']+=$data['task_goods_price']*$data['task_goods_num'];
					unset($data['goodsNum'],$data['goodsLink'],$data['goodsPrice'],$data['goodsImg'],$data['searchPosition']);
					$taskPrice=$taskPrice+floor($data['task_goods_price']*$data['task_goods_num']/200.001)*0.5;
					if($taskPrice<=0){
						echo json_encode(array("status"=>2,"msg"=>"佣金异常！"));exit;
					}
					$data['task_commission']=$taskPrice;
					$data['task_serial']='T'.substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
					$task=new Task();
					if(!$task->save($data)){
						$this->db->rollback();
						echo json_encode(array("status"=>2,"msg"=>"请检查输入或稍候重试！"));exit;
					}
					//计算要扣除的冻结金额总数
					if($data['task_return_type']==1){
						if($data['task_pay_type']==1){
							//如果返款方式为账户余额，支付类型为刷手垫付，则从余额中扣除商品总价、佣金、任务数量的总和作为冻结金额
							$total=$data['task_total_price'] + $taskPrice + $data['task_num'];
						}elseif($data['task_pay_type']==2){
							//如果返款方式为账户余额，支付类型为商家远程，则从余额中扣除商品佣金、任务数量的总和作为冻结金额
							$total=$taskPrice + $data['task_num'];
						}
					}else{
						//如果返款方式不是账户余额，则从余额中扣除任务数量作为冻结金额
						$total=$data['task_num'];
					}
					//若会员现有冻结金额不足，则从会员余额中进行扣除
					if($user->user_freeze_money < $total){
						$differ=$total - $user->user_freeze_money;
						$money=$user->user_money - $differ;
						$freezeMoney=$user->user_freeze_money + $differ;
						if($money<0){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"余额不足以支付冻结金额，请充值！"));exit;
						}elseif(!$user->save(array("user_money"=>$money,"user_freeze_money"=>$freezeMoney))){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请检查输入或稍候重试！"));exit;
						}
						//资金明细添加记录
						$moneyDetail=new MoneyDetail();
						$info=array("user_id"=>$userId,"type"=>"发布任务","change_money"=>-1*$differ,"balance"=>$money,"change_time"=>time());
						if(!$moneyDetail->save($info)){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请检查输入或稍候重试！"));exit;
						}
					}
					//如果为普通商家，则判断并更新会员发布点数
					if($user->user_type==1){
						$releasePoint=$user->user_release_point - $data['task_num'];
						if($releasePoint<0){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"发布点不足，请充值！"));exit;
						}
						if(!$user->save(array("user_release_point"=>$releasePoint))){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请检查输入或稍候重试！"));exit;
						}
					}
					$this->db->commit();
					echo json_encode(array("status"=>1));exit;
				}else{
					echo json_encode(array("status"=>2,"msg"=>"您还未登录！"));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
    //任务模板上架/下架操作
    public function templateoprateAction(){
        if($this->request->isPost()) {
            if ($this->request->isAjax()) {
				if($this->session->has('userId')){
					$data=$this->request->getPost();
					$task=Task::findFirst($data['id']);
					$task->save(array("task_is_release"=>$data['v']));
					if ($this->db->affectedRows()) {
						echo json_encode(array("status"=>1));exit;
					}else{
						echo json_encode(array("status"=>2,"msg"=>"操作失败，请稍候重试！"));exit;
					}
				}else{
					echo json_encode(array("status"=>2,"msg"=>"您还未登录！"));exit;
				}
            }else{
				$this->response->redirect("/");
			}
        }else{
			$this->response->redirect("/");
		}
    }
	//删除任务模板
	public function deletetemplateAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				if($this->session->has('userId')){
					$data=$this->request->getPost();
					$userId=$this->session->get('userId');
					$this->db->begin();
					$user=User::findFirst($userId);
					$task=Task::findFirst($data['id']);
					//计算要返还的冻结金额
					if($task->task_return_type==1){
						if($task->task_pay_type==1){
							$total=$task->task_total_price + $task->task_commission + $task->task_num;
						}elseif($task->task_pay_type==2){
							$total=$task->task_commission + $task->task_num;
						}
					}else{
						$total=$task->task_num;
					}
					$freezeMoney=$user->user_freeze_money - $total;
					//计算要返还的发布点
					$releasePoint=$user->user_release_point + $task->task_num;
					//计算返还后会员余额
					$money=$user->user_money + $total;
					//更新会员余额、发布点、冻结金额
					if(!$user->save(array("user_release_point"=>$releasePoint,"user_freeze_money"=>$freezeMoney,"user_money"=>$money))){
						$this->db->rollback();
						echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
					}
					//更新任务状态为不保存不发布
					if(!$task->save(array("task_is_save"=>2,"task_is_release"=>2))){
						$this->db->rollback();
						echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
					}
					//资金明细添加记录
					$moneyDetail=new MoneyDetail();
					$info=array("user_id"=>$userId,"type"=>"删除任务","change_money"=>$total,"balance"=>$money,"change_time"=>time());
					if(!$moneyDetail->save($info)){
						$this->db->rollback();
						echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
					}
					$this->db->commit();
					echo json_encode(array("status"=>1));exit;
				}else{
					echo json_encode(array("status"=>2,"msg"=>"您还未登录！"));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
	//更新任务模板库存
	public function updatetemplateAction(){
		if($this->request->isPost()) {
			if ($this->request->isAjax()) {
				if($this->session->has('userId')){
					$data=$this->request->getPost();
					$userId=$this->session->get('userId');
					$taskNum=intval($data['task_num']);
					if(intval($data['task_id']) <= 0){
						echo json_encode(array("status"=>2,"msg"=>"请检查输入或稍候重试！"));exit;
					}
					if($taskNum <= 0){
						echo json_encode(array("status"=>2,"msg"=>"库存数量只能是大于0的整数！"));exit;
					}
					$this->db->begin();
					$user=User::findFirst($userId);
					$task=Task::findFirst($data['task_id']);
					if($taskNum == $task->task_num){
						echo json_encode(array("status"=>2,"msg"=>"请不要输入与当前库存相同的数量！"));exit;
					}elseif($taskNum < $task->task_num){
						$differ=$task->task_num-$taskNum;
						$releasePoint=$user->user_release_point+$differ;
						$money=$user->user_money + $differ;
						$freezeMoney=$user->user_freeze_money - $differ;
						if(!$user->save(array("user_money"=>$money,"user_freeze_money"=>$freezeMoney,"user_release_point"=>$releasePoint))){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
						}
						//资金明细添加记录
						$moneyDetail=new MoneyDetail();
						$info=array("user_id"=>$userId,"type"=>"更新库存","change_money"=>$differ,"balance"=>$money,"change_time"=>time());
						if(!$moneyDetail->save($info)){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
						}
					}elseif($taskNum > $task->task_num){
						$differ=$taskNum - $task->task_num;
						$releasePoint=$user->user_release_point - $differ;
						$money=$user->user_money - $differ;
						$freezeMoney=$user->user_freeze_money + $differ;
						if($releasePoint<0){
							echo json_encode(array("status"=>2,"msg"=>"您的发布点不足，请购买发布点！"));exit;
						}
						if($money < 0){
							echo json_encode(array("status"=>2,"msg"=>"您的余额不足以支付要扣除的冻结金额，请充值！"));exit;
						}
						if(!$user->save(array("user_money"=>$money,"user_freeze_money"=>$freezeMoney,"user_release_point"=>$releasePoint))){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
						}
						//资金明细添加记录
						$moneyDetail=new MoneyDetail();
						$info=array("user_id"=>$userId,"type"=>"更新库存","change_money"=>-1*$differ,"balance"=>$money,"change_time"=>time());
						if(!$moneyDetail->save($info)){
							$this->db->rollback();
							echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
						}
					}
					if(!$task->save(array("task_num"=>$taskNum))){
						$this->db->rollback();
						echo json_encode(array("status"=>2,"msg"=>"请稍候重试！"));exit;
					}
					$this->db->commit();
					echo json_encode(array("status"=>1));exit;
				}else{
					echo json_encode(array("status"=>2,"msg"=>"您还未登录！"));exit;
				}
			}else{
				$this->response->redirect("/");
			}
		}else{
			$this->response->redirect("/");
		}
	}
}